<template>
    <div class="app-container">
        <div class="filter-container">
            <el-input v-model="query.name" class="filter-item w-200" size="medium" placeholder="名称"></el-input>
            <el-input v-model="query.phone" class="filter-item w-200" size="medium" placeholder="手机号码"></el-input>
            <div class="filter-item block">
                <el-date-picker
                        size="medium"
                        value-format="yyyy-MM"
                        v-model="query.date"
                        type="month"
                        placeholder="选择月">
                </el-date-picker>
            </div>
            <el-button class="filter-item" size="medium" icon="el-icon-search" @click="fetchList(true)">搜 索</el-button>
            <el-button class="filter-item" size="medium" icon="el-icon-download" @click="downloadOrder">导 出</el-button>
        </div>
        <el-table :data="list" v-loading="loading" border style="width: 100%">
            <el-table-column width="50px" label="#" align="center">
                <template slot-scope="scope" >
                    {{query.size * (query.page-1) + scope.$index + 1}}
                </template>
            </el-table-column>
            <el-table-column prop="name" label="名称" align="center"></el-table-column>
            <el-table-column prop="role_name" label="角色" align="center"></el-table-column>
            <el-table-column prop="phone" label="手机号码" align="center"></el-table-column>
            <el-table-column prop="normal" label="报餐数" align="center"></el-table-column>
            <el-table-column prop="children" label="子女餐数" align="center"></el-table-column>
            <el-table-column prop="addition" label="加餐数" align="center"></el-table-column>
            <el-table-column prop="official" label="公务餐数" align="center"></el-table-column>
        </el-table>
        <div class="pagination-container">
            <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="query.page"
                    :page-sizes="[10, 20, 30, 50]"
                    :page-size="query.size"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="total">
            </el-pagination>
        </div>
    </div>
</template>

<script>
  import { fetchMealStatistics } from '@/api/book-order'
  export default {
    name: 'MealStatistics',
    data() {
      return {
        loading: false,
        list: [],
        query: {
          page: 1,
          size: 10,
          date: this.$moment().format('YYYY-MM'),
          phone: '',
          name: '',
          type: ''
        },
        total: 0
      }
    },
    methods: {
      fetchList(resetPage = false) {
        this.query.type = ''
        this.loading = true
        if (resetPage === true) {
          this.query.page = 1
        }
        // 获取当前学校下的菜品列表
        fetchMealStatistics(this.query).then(res => {
          this.list = res.data
          this.loading = false
          this.total = res.meta.total
        })
      },
      handleSizeChange(size) {
        this.query.size = size
        this.fetchList()
      },
      handleCurrentChange(page) {
        this.query.page = page
        this.fetchList()
      },
      // 导出
      downloadOrder() {
        this.$confirm('确定导出?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.query.type = 'export'
          fetchMealStatistics(this.query).then(res => {
            if (res.length === 0) {
              this.$message('无数据')
            } else {
              const filename = this.query.date
              const wopts = { bookType: 'xlsx', bookSST: false, type: 'binary' }
              const list = res
              const tHeader = ['名称', '角色', '手机号码', '报餐数', '子女餐数', '加餐数', '公务餐数']
              const filterVal = ['name', 'role_name', 'phone', 'normal', 'children', 'addition', 'official']
              const data = this.formatJson(filterVal, list)
              data.unshift(tHeader)
              const wb = { SheetNames: [], Sheets: {}}
              const ws = this.sheet_from_array_of_arrays(data)
              ws['!cols'] = []
              for (let n = 0; n !== filterVal.length; ++n) {
                ws['!cols'].push({
                  wpx: 100
                })
              }
              ws['!rows'] = [{ hpx: 20 }]
              wb.SheetNames.push(filename)
              wb.Sheets[filename] = ws
              const tmpDown = new Blob([this.s2ab(this.$xlsx.write(wb, wopts))], { type: 'application/octet-stream' })
              this.$fileSaver.saveAs(tmpDown, filename + '.xlsx')
            }
          })
        }).catch(() => {})
      },
      sheet_from_array_of_arrays(data) {
        const ws = {}
        const range = { s: { c: 10000000, r: 10000000 }, e: { c: 0, r: 0 }}
        for (let R = 0; R !== data.length; ++R) {
          for (let C = 0; C !== data[R].length; ++C) {
            if (range.s.r > R) range.s.r = R
            if (range.s.c > C) range.s.c = C
            if (range.e.r < R) range.e.r = R
            if (range.e.c < C) range.e.c = C
            const cell = {
              v: data[R][C],
              s: {
                alignment: { horizontal: 'center', vertical: 'center' }
              }
            }
            if (cell.v == null) continue
            const cell_ref = this.$xlsx.utils.encode_cell({ c: C, r: R })
            if (typeof cell.v === 'number') {
              cell.t = 'n'
            } else if (typeof cell.v === 'boolean') {
              cell.t = 'b'
            } else if (cell.v instanceof Date) {
              cell.t = 'n'
              cell.z = this.$xlsx.SSF._table[14]
              cell.v = this.datenum(cell.v)
            } else {
              cell.t = 's'
            }
            ws[cell_ref] = cell
          }
        }
        if (range.s.c < 10000000) ws['!ref'] = this.$xlsx.utils.encode_range(range)
        return ws
      },
      datenum(v, date1904) {
        if (date1904) v += 1462
        const epoch = Date.parse(v)
        return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000)
      },
      s2ab(s) {
        const buf = new ArrayBuffer(s.length)
        const view = new Uint8Array(buf)
        for (let i = 0; i !== s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF
        return buf
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map(v => filterVal.map(j => v[j]))
      }
    },
    created() {
      this.fetchList()
    }
  }
</script>

<style scoped>

</style>
